﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Storage;
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using YesBlog.Infrastructure.Context;

namespace YesBlog.Infrastructure.UnitOfWork
{
    public class UnitOfWork : IUnitOfWork
    {
        private IDbContext _dbContext;
        private IDbContextTransaction _dbTransaction;


        public UnitOfWork(IDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public void BeginTransaction()
        {
            var innerContext = (DbContext)_dbContext;
            _dbTransaction = innerContext.Database.BeginTransaction();
        }

        public void RegisterAdd<TEntity>(TEntity entity)
            where TEntity : class
        {
            _dbContext.Set<TEntity>().Add(entity);
        }

        public void RegisterUpdate<TEntity>(TEntity entity)
            where TEntity : class
        {
            var innerContext = (DbContext)_dbContext;
            innerContext.Entry<TEntity>(entity).State = EntityState.Modified;
        }


        public void RegisterDelete<TEntity>(TEntity entity)
            where TEntity : class
        {
            _dbContext.Set<TEntity>().Remove(entity);
        }

        public bool Commit()
        {
            return _dbContext.SaveChanges() > 0;
        }

        public void Rollback()
        {
            if (_dbTransaction != null)
                _dbTransaction.Rollback();
        }
    }
}
